<template>
  <div class="performance-report">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :model="searchForm" ref="searchFormRef" inline>
        <el-form-item label="统计周期" prop="period">
          <el-select
            v-model="searchForm.period"
            placeholder="请选择统计周期"
            style="width: 120px"
          >
            <el-option label="月度" value="month" />
            <el-option label="季度" value="quarter" />
            <el-option label="年度" value="year" />
          </el-select>
        </el-form-item>
        <el-form-item label="统计时间" prop="dateRange">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="部门" prop="department">
          <el-select
            v-model="searchForm.department"
            placeholder="请选择部门"
            clearable
            style="width: 120px"
          >
            <el-option label="信贷部" value="信贷部" />
            <el-option label="风控部" value="风控部" />
            <el-option label="运营部" value="运营部" />
            <el-option label="客服部" value="客服部" />
            <el-option label="财务部" value="财务部" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleExport">导出</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stat-row">
      <el-col :span="6">
        <el-card class="stat-card">
          <template #header>
            <div class="stat-header">
              <span>总绩效金额</span>
              <el-tag size="small" type="success">本期</el-tag>
            </div>
          </template>
          <div class="stat-content">
            <div class="stat-value">{{ formatMoney(stats.totalPerformance) }}</div>
            <div class="stat-compare">
              环比
              <span :class="stats.performanceRate >= 0 ? 'up' : 'down'">
                {{ stats.performanceRate >= 0 ? '+' : '' }}{{ stats.performanceRate }}%
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <template #header>
            <div class="stat-header">
              <span>目标完成率</span>
              <el-tag size="small" type="primary">本期</el-tag>
            </div>
          </template>
          <div class="stat-content">
            <div class="stat-value">{{ stats.completionRate }}%</div>
            <div class="stat-compare">
              环比
              <span :class="stats.completionRateChange >= 0 ? 'up' : 'down'">
                {{ stats.completionRateChange >= 0 ? '+' : '' }}{{ stats.completionRateChange }}%
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <template #header>
            <div class="stat-header">
              <span>客户数量</span>
              <el-tag size="small" type="warning">本期</el-tag>
            </div>
          </template>
          <div class="stat-content">
            <div class="stat-value">{{ stats.customerCount }}</div>
            <div class="stat-compare">
              环比
              <span :class="stats.customerCountRate >= 0 ? 'up' : 'down'">
                {{ stats.customerCountRate >= 0 ? '+' : '' }}{{ stats.customerCountRate }}%
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <template #header>
            <div class="stat-header">
              <span>贷款笔数</span>
              <el-tag size="small" type="info">本期</el-tag>
            </div>
          </template>
          <div class="stat-content">
            <div class="stat-value">{{ stats.loanCount }}</div>
            <div class="stat-compare">
              环比
              <span :class="stats.loanCountRate >= 0 ? 'up' : 'down'">
                {{ stats.loanCountRate >= 0 ? '+' : '' }}{{ stats.loanCountRate }}%
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表展示 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="16">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">绩效趋势</div>
          </template>
          <div class="chart-content" ref="trendChartRef"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">员工绩效排名</div>
          </template>
          <div class="chart-content" ref="rankingChartRef"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">部门绩效分布</div>
          </template>
          <div class="chart-content" ref="departmentChartRef"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">产品绩效分布</div>
          </template>
          <div class="chart-content" ref="productChartRef"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 明细数据 -->
    <el-card class="table-card">
      <template #header>
        <div class="table-header">绩效明细</div>
      </template>
      <el-table
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        border
        stripe
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="date" label="日期" width="100" />
        <el-table-column prop="staffName" label="员工姓名" width="100" />
        <el-table-column prop="department" label="所属部门" width="100" />
        <el-table-column prop="targetAmount" label="目标金额" width="120">
          <template #default="scope">
            {{ formatMoney(scope.row.targetAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="actualAmount" label="实际金额" width="120">
          <template #default="scope">
            {{ formatMoney(scope.row.actualAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="completionRate" label="完成率" width="100">
          <template #default="scope">
            <el-tag :type="getCompletionRateTag(scope.row.completionRate)">
              {{ scope.row.completionRate }}%
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="customerCount" label="客户数量" width="100" />
        <el-table-column prop="loanCount" label="贷款笔数" width="100" />
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import axios from 'axios'

// 搜索表单
const searchForm = reactive({
  period: 'month',
  dateRange: [],
  department: ''
})

// 统计数据
const stats = reactive({
  totalPerformance: 0,
  performanceRate: 0,
  completionRate: 0,
  completionRateChange: 0,
  customerCount: 0,
  customerCountRate: 0,
  loanCount: 0,
  loanCountRate: 0
})

// 表格数据
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableData = ref([])

// 图表引用
const trendChartRef = ref(null)
const rankingChartRef = ref(null)
const departmentChartRef = ref(null)
const productChartRef = ref(null)

// 图表实例
let trendChart = null
let rankingChart = null
let departmentChart = null
let productChart = null

// 获取统计数据
const fetchStats = async () => {
  try {
    const res = await axios.get('/api/report/performance/stats')
    if (res.data.code === 200) {
      Object.assign(stats, res.data.data)
    }
  } catch (error) {
    console.error('获取统计数据失败', error)
  }
}

// 获取图表数据
const fetchChartData = async () => {
  try {
    const res = await axios.get('/api/report/performance/charts')
    if (res.data.code === 200) {
      const { months, performanceTrend, staffRanking, departmentDistribution, productDistribution } = res.data.data
      updateCharts(months, performanceTrend, staffRanking, departmentDistribution, productDistribution)
    }
  } catch (error) {
    console.error('获取图表数据失败', error)
  }
}

// 获取表格数据
const fetchTableData = async () => {
  loading.value = true
  try {
    const res = await axios.get('/api/report/performance/list', {
      params: {
        currentPage: currentPage.value,
        pageSize: pageSize.value,
        department: searchForm.department,
        period: searchForm.period,
        dateRange: searchForm.dateRange
      }
    })
    if (res.data.code === 200) {
      tableData.value = res.data.data.list
      total.value = res.data.data.total
    }
  } catch (error) {
    console.error('获取表格数据失败', error)
  } finally {
    loading.value = false
  }
}

// 更新图表
const updateCharts = (months, performanceTrend, staffRanking, departmentDistribution, productDistribution) => {
  // 绩效趋势图
  trendChart.setOption({
    xAxis: {
      data: months
    },
    series: [
      {
        name: '实际绩效',
        data: performanceTrend.actual
      },
      {
        name: '目标绩效',
        data: performanceTrend.target
      }
    ]
  })

  // 员工绩效排名图
  rankingChart.setOption({
    yAxis: {
      data: staffRanking.map(item => item.name)
    },
    series: [
      {
        data: staffRanking.map(item => item.value)
      }
    ]
  })

  // 部门绩效分布图
  departmentChart.setOption({
    series: [
      {
        data: departmentDistribution
      }
    ]
  })

  // 产品绩效分布图
  productChart.setOption({
    series: [
      {
        data: productDistribution
      }
    ]
  })
}

// 初始化图表
const initCharts = () => {
  // 绩效趋势图
  trendChart = echarts.init(trendChartRef.value)
  trendChart.setOption({
    title: {
      text: '绩效趋势'
    },
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        let result = params[0].name + '<br/>'
        params.forEach(param => {
          result += param.seriesName + ': ' + formatMoney(param.value) + '<br/>'
        })
        return result
      }
    },
    legend: {
      data: ['实际绩效', '目标绩效']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: function(value) {
          return (value / 10000).toFixed(0) + '万'
        }
      }
    },
    series: [
      {
        name: '实际绩效',
        type: 'line',
        smooth: true,
        emphasis: {
          focus: 'series'
        },
        itemStyle: {
          color: '#409EFF'
        },
        data: []
      },
      {
        name: '目标绩效',
        type: 'line',
        smooth: true,
        emphasis: {
          focus: 'series'
        },
        itemStyle: {
          color: '#E6A23C'
        },
        lineStyle: {
          type: 'dashed'
        },
        data: []
      }
    ]
  })

  // 员工绩效排名图
  rankingChart = echarts.init(rankingChartRef.value)
  rankingChart.setOption({
    title: {
      text: '员工绩效排名'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params) {
        return params[0].name + ': ' + formatMoney(params[0].value)
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      axisLabel: {
        formatter: function(value) {
          return (value / 10000).toFixed(0) + '万'
        }
      }
    },
    yAxis: {
      type: 'category',
      data: [],
      inverse: true
    },
    series: [
      {
        name: '绩效金额',
        type: 'bar',
        data: [],
        itemStyle: {
          color: function(params) {
            // 前三名使用不同颜色
            const colors = ['#F56C6C', '#E6A23C', '#67C23A', '#409EFF', '#909399']
            return params.dataIndex < 3 ? colors[params.dataIndex] : colors[3]
          }
        },
        label: {
          show: true,
          position: 'right',
          formatter: function(params) {
            return formatMoney(params.value)
          }
        }
      }
    ]
  })

  // 部门绩效分布图
  departmentChart = echarts.init(departmentChartRef.value)
  departmentChart.setOption({
    title: {
      text: '部门绩效分布'
    },
    tooltip: {
      trigger: 'item',
      formatter: function(params) {
        return params.name + ': ' + formatMoney(params.value) + ' (' + params.percent + '%)'
      }
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center'
    },
    series: [
      {
        name: '部门绩效',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: []
      }
    ]
  })

  // 产品绩效分布图
  productChart = echarts.init(productChartRef.value)
  productChart.setOption({
    title: {
      text: '产品绩效分布'
    },
    tooltip: {
      trigger: 'item',
      formatter: function(params) {
        return params.name + ': ' + formatMoney(params.value) + ' (' + params.percent + '%)'
      }
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center'
    },
    series: [
      {
        name: '产品绩效',
        type: 'pie',
        radius: '50%',
        data: [],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  })

  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    trendChart?.resize()
    rankingChart?.resize()
    departmentChart?.resize()
    productChart?.resize()
  })
}

// 查询
const handleSearch = () => {
  currentPage.value = 1
  fetchTableData()
}

// 重置
const handleReset = () => {
  searchForm.period = 'month'
  searchForm.dateRange = []
  searchForm.department = ''
  handleSearch()
}

// 导出
const handleExport = () => {
  ElMessage.success('导出成功')
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchTableData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchTableData()
}

// 格式化金额
const formatMoney = (value) => {
  if (!value && value !== 0) return '0'
  
  // 转为字符串，并保留两位小数
  const str = Number(value).toFixed(2)
  
  // 分割整数和小数部分
  const parts = str.split('.')
  const integerPart = parts[0]
  const decimalPart = parts.length > 1 ? '.' + parts[1] : ''
  
  // 添加千位分隔符
  const regex = /(\d)(?=(\d{3})+$)/g
  const formattedInteger = integerPart.replace(regex, '$1,')
  
  return formattedInteger + decimalPart
}

// 获取完成率标签类型
const getCompletionRateTag = (rate) => {
  if (rate >= 100) return 'success'
  if (rate >= 80) return 'warning'
  return 'danger'
}

// 组件挂载后初始化图表和获取数据
onMounted(async () => {
  initCharts()
  await fetchStats()
  await fetchChartData()
  await fetchTableData()
})
</script>

<style scoped>
.performance-report {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.stat-row {
  margin-bottom: 20px;
}

.stat-card {
  .stat-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .stat-content {
    text-align: center;

    .stat-value {
      font-size: 24px;
      font-weight: bold;
      margin-bottom: 10px;
    }

    .stat-compare {
      color: #666;
      font-size: 14px;

      .up {
        color: #67c23a;
      }

      .down {
        color: #f56c6c;
      }
    }
  }
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  .chart-header {
    font-weight: bold;
  }

  .chart-content {
    height: 300px;
  }
}

.table-card {
  margin-bottom: 20px;

  .table-header {
    font-weight: bold;
  }
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-card__body) {
  padding: 20px;
}
</style>
